package me.linkcn.ydtxl.server.resources;

import me.linkcn.ydtxl.server.Application;
import me.linkcn.ydtxl.server.objects.Account;
import me.linkcn.ydtxl.server.objects.Error;
import me.linkcn.ydtxl.server.objects.ObjectsFacade;
import me.linkcn.ydtxl.server.objects.Result;
import org.restlet.data.Form;
import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ServerResource;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: cmcc
 * Date: 11-8-15
 * Time: 上午12:38
 */
public class BaseResource extends ServerResource {
    private Account currentAccount;

    public BaseResource() {
        super();
//        if (this.currentAccount == null) {
//            if (getRequest().getChallengeResponse() != null) {
//                this.currentAccount = getObjectsFacade().getAccountByLoginPwd(
//                        getRequest().getChallengeResponse().getIdentifier(),
//                        getRequest().getChallengeResponse().getSecret());
//            }
//        }
    }

    protected void allowOtherHost() {
        Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");
        if (responseHeaders == null) {
            responseHeaders = new Form();
            getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
        }
        responseHeaders.add("Access-Control-Allow-Origin", "*");
    }

    protected ObjectsFacade getObjectsFacade() {
        final Application application = (Application) getApplication();
        return application.getObjectsFacade();
    }

    protected Representation generateErrorRepresentation(String errorMessage, String errorCode) {
        JacksonRepresentation result = null;
        // This is an error
        // Generate the output representation
        try {
            Error error = new Error();
            error.setErrorMessage(errorMessage);
            error.setErrorCode(errorCode);
            result = new JacksonRepresentation(error);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    protected Representation generateResultRepresentation(boolean trueOrFalse) {
        JacksonRepresentation  out = null;
        try {
            Result result = new Result();
            result.setResult(trueOrFalse);
            out = new JacksonRepresentation(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return out;
    }
}
